<template>
  <div class="login-container">
    <el-form
      class="login-form"
      ref="userForm"
      :model="loginForm"
      :rules="loginRules"
    >
      <div class="admin-logo">
        <img class="logo" src="../../assets/vue.svg" alt="logo" />
        <h1 class="name">Vue3 Admin</h1>
      </div>
      <el-form-item prop="username">
        <el-input placeholder="请输入用户名" v-model="loginForm.username">
          <template #prepend>
            <span class="svg-container">
              <svg-icon icon-name="ant-design:user-outlined"></svg-icon>
            </span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          placeholder="请输入密码"
          autocomplete="on"
          show-password
          v-model="loginForm.password"
        >
          <template #prepend>
            <span class="svg-container">
              <svg-icon icon-name="ant-design:lock-outlined"></svg-icon>
            </span>
          </template>
        </el-input>
      </el-form-item>
      <!-- 登录按钮 -->
      <el-button
        type="primary"
        w-full
        mb-30px
        :loading="loading"
        @click="handleLogin"
        >登录</el-button
      >
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { useUserStore } from "@/stores/userStore";
import type { FormInstance } from "element-plus";
import { useQuery } from "@/hooks/useQuery";

const router = useRouter();
const loading = ref(false);
const useStore = useUserStore();

const { redirect, otherQuery } = useQuery();
console.log("redirect=", redirect.value, "otherQuery=", otherQuery.value);

const loginState = reactive({
  loginForm: {
    username: "",
    password: ""
  },
  loginRules: {
    username: [{ required: true, trigger: "blur", message: "用户名不能为空" }],
    password: [{ required: true, trigger: "blur", message: "密码不能为空" }]
  }
});
const { loginForm, loginRules } = loginState;

const userFormInstance = useTemplateRef<FormInstance>("userForm");

const handleLogin = () => {
  userFormInstance.value?.validate(async (valid) => {
    if (valid) {
      let r = await useStore.login(loginForm);
      if (r.code === 200 && r.data.token != "") {
        // 解析出一个重定向的路径  + 其他的查询参数 http://localhost:5173/login?redirect=/documentation/index&a=1&b=2
        router.push({ path: redirect.value || "/", query: otherQuery.value });
      }
    }
  });
};
</script>
<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  @apply w-full;
  .login-form {
    @apply w-500px mx-auto;
  }
  .admin-logo {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
